package com.gainloop.Api;

import org.alexd.jsonrpc.JSONRPCException;
import org.json.JSONException;

import com.gainloop.Api.Entity.Session;
import com.gainloop.Api.Entity.User;
import com.gainloop.Data.Registry;

/**
 * @author owner
 * 
 */
public class Auth extends ApiAbstract {
	
	static private Auth _instance = null;
	
	public static Auth getInstance()
	{
		if(_instance == null) {
			_instance = new Auth();
		}
		
		return _instance;
	}

	public Session updateSession(Session session)
			throws JSONRPCException {
		try {
			ApiResponseObject<Session> res =  new ApiResponseObject<Session>(GetClient().callJSONObject(
					"auth.updateSession", session), Session.class);
			
			if(res.getReturnCode() != 0) {
				if(res.getReturnCode() == -1) {
					throw new ApiException("Invalid session", res.getReturnCode());
				}
				throw new ApiException("wrong usage: ", res);
			}
			
			return res.getData();
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}

	public User getUser(Session session)
			throws JSONRPCException {
		try {
			ApiResponseObject<User> res =  new ApiResponseObject<User>(GetClient().callJSONObject(
					"auth.getUser", session.toObject()), User.class);
			
			if(res.getReturnCode() != 0) {
				if(res.getReturnCode() == -1) {
					return null;
				}
				throw new ApiException("wrong usage: ", res);
			}
			
			return res.getData();
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}
	
	public int signInFb(long userFbId, String token) throws JSONRPCException {
		
		try {
			ApiResponse res = new ApiResponse(GetClient().callJSONObject("auth.signInFb", userFbId, token));
			
			if(res.getReturnCode() != 0) {
				throw new ApiException("wrong usage: ", res);
			}

			User user = User.fromObject(res.getDataJsonObject().getJSONObject("user"), User.class);
			Session session = Session.fromObject(res.getDataJsonObject().getJSONObject("session"), Session.class);
			
			Registry.SetUser(user);
			Registry.SetSession(session);
			
			return res.getReturnCode();
		} catch (JSONException e) {
			throw new ApiException("invalid respond");
		}
	}

	

}
